package com.martin.lib_base.utils

import android.content.Intent
import com.martin.lib_base.LibBase
import com.martin.lib_base.bean.UserBean
import com.martin.lib_base.constant.ConstantKey
import com.martin.lib_base.ktx.launchCollect
import com.martin.lib_base.ktx.logd
import com.martin.lib_base.ktx.loge
import com.martin.lib_base.ktx.toJson
import com.martin.lib_base.ktx_live.buildRequest
import com.martin.lib_base.net.NetApply
import com.tencent.mmkv.MMKV
import dev.DevUtils
import dev.utils.app.ActivityUtils
import dev.utils.app.NetWorkUtils
import kotlinx.coroutines.flow.MutableStateFlow

object UserUtil {

    private val mmkv = MMKV.defaultMMKV()

    // 用户信息
    val userBean = MutableStateFlow(UserBean())

    // 登录状态
    fun getIsLogin(): Boolean {
        return mmkv.decodeBool(ConstantKey.IS_LOGIN, false)
    }

    fun initUser() {
        mmkv.apply {
            LibBase.isLogin.value = getIsLogin()
            if (getIsLogin()) {
                // 反序列化: data->bean
                decodeParcelable(ConstantKey.USER_INFO, UserBean::class.java)?.let {
                    LibBase.userInfo.value = it
                }
                loge("获取token ${LibBase.token}")
                loge("获取用户信息 ${LibBase.userInfo.value.toJson()}")
                refreshUserInfo()
            }
        }
    }

    /**
     * 刷新用户数据
     */
    fun refreshUserInfo() {
        if (!NetWorkUtils.isAvailableByPing()) {
            return
        }
        launchCollect({
            NetApply.api.getUserInfo(
                buildRequest("User.GetBaseInfo")
            )
        }) {
            onSuccess = {
                it.info?.let { info ->
                    mmkv.apply {
                        handleLogin(info)
                    }
                    userBean.tryEmit(info)
                }
            }
        }
    }

    /**
     * 处理登录
     */
    fun handleLogin(userBean: UserBean) {
        mmkv.apply {
            encode(ConstantKey.IS_LOGIN, true)
            encode(ConstantKey.ACCOUNT, userBean.mobile ?: "")
            encode(ConstantKey.USER_ID, userBean.id ?: -1)
            encode(ConstantKey.TOKEN, userBean.token ?: "")
            encode(ConstantKey.USER_INFO, userBean.toJson(false))
        }
        LibBase.userInfo.value = userBean
        LibBase.isLogin.value = true
    }

    /**
     * 处理退出登录
     */
    fun handleLogout() {
        val token = LibBase.token
        LibBase.userInfo.value?.let {
            launchCollect({
                NetApply.api.logout(
                    buildRequest(
                        "Login.Logout",
                        mapOf("uid" to (it.id ?: -1), "token" to token)
                    )
                )
            }) {
                onSuccess = {
                    logd("退出登录成功")
                }
            }
        }

        mmkv.apply {
            encode(ConstantKey.IS_LOGIN, false)
            remove(ConstantKey.ACCOUNT)
            remove(ConstantKey.USER_ID)
            remove(ConstantKey.TOKEN)
            remove(ConstantKey.USER_INFO)
        }
        LibBase.isLogin.value = false

        startLoginActivityAndFinishOthers()
    }

    /**
     * 跳转登录页并关闭其他页面
     */
    fun startLoginActivityAndFinishOthers() {
        // 跳转登录页
        val activity = DevUtils.getTopActivity()
        val loginActivityClazz = Class.forName("com.example.androidframework.ui.login.LoginActivity")
        activity.startActivity(Intent(activity, loginActivityClazz))
        // 退出所有其他activity
        ActivityUtils.getManager().finishAllActivityToIgnore(loginActivityClazz)
    }

    /**
     * 展示日志
     */
    private fun showLog(msg: String) {
         loge("用户工具: $msg")
    }
}